package com.crdeng.system.controller;


import com.crdeng.handler.BusinessException;
import com.crdeng.response.Result;
import com.crdeng.response.ResultCode;
import com.crdeng.system.entity.Department;
import com.crdeng.system.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 部门表 前端控制器
 * </p>
 *
 * @author crdeng
 * @since 2020-11-18
 *
 */
@Api(value = "部门模块",tags = "部门模块")
@RestController
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "所有部门及部门人数",notes = "查询所有的部门和部门的人数")
    @GetMapping("/findDeptAndCount")
    public Result finDeptAndCount() {
        List<Department> deptAndCount = departmentService.findDeptAndCount();
        if (deptAndCount==null){
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(), ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }

        return Result.ok().data("deptList",deptAndCount);
    }

    @ApiOperation(value = "部门列表",notes = "查询部门列表")
    @GetMapping("/finDeptList")
    public Result finDeptList (){
        List<Department> deptList = departmentService.list();
        if (deptList==null){
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(), ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }

        return Result.ok().data("deptList",deptList);
    }



    @ApiOperation(value = "删除部门",notes = "删除部门")
    @GetMapping("/deleteDept")
    public Result deleteDept (@RequestParam Long id){
        boolean flag = departmentService.removeById(id);
        if (!flag){
            throw new BusinessException(ResultCode.DEPARTMENT_NOT_EXIST.getCode(), ResultCode.DEPARTMENT_NOT_EXIST.getMessage());
        }

        return Result.ok().message("删除部门成功");
    }



    @ApiOperation(value = "添加部门",notes = "添加部门")
    @PostMapping("/addDept")
    public Result addDept (@RequestBody Department department){
        System.out.println(department);
        department.setId(null);
        Date date = new Date();
        department.setCreateTime(date);
        department.setModifiedTime(date);
        boolean flag = departmentService.save(department);
        if (!flag){
            return Result.error().message("添加部门失败");
        }

        return Result.ok().message("添加部门成功");
    }



    @ApiOperation(value = "修改部门",notes = "修改部门信息")
    @PostMapping("/resetDept")
    public Result resetDept (@RequestBody Department department){
        System.out.println(department);
        boolean flag = departmentService.updateById(department);
        if (!flag){
            return Result.error().message("修改部门失败");
        }

        return Result.ok().message("修改部门成功");
    }

}

